package com.example.demo;

import javax.annotation.PostConstruct;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.internals.YmlConfigFile;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.sun.corba.se.spi.activation.IIOP_CLEAR_TEXT.value;

/**
 * Created by BG314005 on 2018/7/20.
 */
@RestController
public class TestApiController {
    @RequestMapping("/apiHello")
    public String test() {
        Config config = ConfigService.getAppConfig();
        String someKey = "test.string.hello";
        String someDefaultValue = "default";
        String value = config.getProperty(someKey, someDefaultValue);
        return value;
    }

    @RequestMapping("/apiHello2")
    public String test2() {
        String somePublicNamespace = "TEST1.BillCodeDefine";
        Config config = ConfigService.getConfig(somePublicNamespace);
        String someKey = "test.string.hello";
        String someDefaultValue = "default";
        String value = config.getProperty(someKey, someDefaultValue);
        return value;
    }

    @PostConstruct
    public void configChangeListener() {
        Config config = ConfigService.getAppConfig();
        config.addChangeListener(new ConfigChangeListener() {
            @Override
            public void onChange(ConfigChangeEvent changeEvent) {
                System.out.println("Changes for namespace " + changeEvent.getNamespace());
                for (String key : changeEvent.changedKeys()) {
                    ConfigChange change = changeEvent.getChange(key);
                    System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
                }
            }
        });
    }

    @RequestMapping("/apiHello3")
    public String aa() {
        ConfigFile configFile = ConfigService.getConfigFile("YML-TEST", ConfigFileFormat.YML);
        String content = configFile.getContent();
        return content;
    }
}
